//
//  RightCollectionVC.m
//  PilotSeries
//
//  Created by 黄立强 on 16/4/6.
//  Copyright © 2016年 leon.huang. All rights reserved.
//


#import "UIScrollView+EmptyDataSet.h"
#import "ChartConfig.h"
#import "PARightCollectionVC.h"
#import "PAAccountManager.h"
#import "PAWebViewCell.h"
#import "PAChartConfigManager.h"
#import "PAChartDetailVC.h"
#import "Masonry.h"
#import "KxMenu.h"
#import "PAGroupManager.h"
#import "HMSegmentedControl.h"
#import "ChartGroup.h"
#import "EditGroupVC.h"
#import "PANavgationVC.h"
#import "PAWKWebViewCell.h"
@interface PARightCollectionVC () <DZNEmptyDataSetSource, DZNEmptyDataSetDelegate,PAWKWebViewCellDelegete>
/**  */
@property (copy, nonatomic) NSString *token;

/** */
@property (assign, nonatomic) NSIndexPath* selectIndex;

/** */
@property (assign, nonatomic) CGRect selectCellFrame;

@property (nonatomic, strong) NSArray * menuItems;

@property (nonatomic, strong) NSMutableArray * chartGroups;

@property (strong, nonatomic) HMSegmentedControl *segmentedControl;
@end

@implementation PARightCollectionVC

static NSString * const reuseIdentifier = @"webview_cell";

- (NSMutableArray *)chartConfigs
{
    if (_chartConfigs == nil) {
        _chartConfigs = [[PAChartConfigManager loadCurrentChartConfigs] mutableCopy];
    }
    return _chartConfigs;
}

- (NSMutableArray *)chartGroups
{
    if (_chartGroups == nil) {
        _chartGroups = [[NSMutableArray alloc] init];
        [_chartGroups addObjectsFromArray:[PAGroupManager loadGroupName]];
        if(![_chartGroups containsObject:@"Default"]){
            [_chartGroups insertObject:@"Default" atIndex:0];
        }
    }
    return _chartGroups;
}
- (id)init
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
   
    return [super initWithCollectionViewLayout:layout];
}
- (NSString *)token
{
    if (_token == nil) {
        _token= [[PAAppContext sharedInstance].token copy];
    }
    return _token;
}

#pragma mark - 懒加载
- (NSArray *)menuItems
{
    if (_menuItems == nil) {
        
        _menuItems = @[
                       [KxMenuItem menuItem:[PAAccountManager getSizeTypeString:PACollectionSizeType1X2] image:nil  tag:PACollectionSizeType1X2 target:self action:@selector(pushMenuItem:)],
                       [KxMenuItem menuItem:[PAAccountManager getSizeTypeString:PACollectionSizeType1X3] image:nil  tag:PACollectionSizeType1X3 target:self action:@selector(pushMenuItem:)],
                       [KxMenuItem menuItem:[PAAccountManager getSizeTypeString:PACollectionSizeType2X2] image:nil  tag:PACollectionSizeType2X2 target:self action:@selector(pushMenuItem:)],
                       [KxMenuItem menuItem:[PAAccountManager getSizeTypeString:PACollectionSizeType1X5] image:nil  tag:PACollectionSizeType1X5 target:self action:@selector(pushMenuItem:)],
                       [KxMenuItem menuItem:[PAAccountManager getSizeTypeString:PACollectionSizeType2X3] image:nil tag:PACollectionSizeType2X3 target:self action:@selector(pushMenuItem:)],
                       [KxMenuItem menuItem:[PAAccountManager getSizeTypeString:PACollectionSizeType2X4] image:nil tag:PACollectionSizeType2X4 target:self action:@selector(pushMenuItem:)],
                       [KxMenuItem menuItem:[PAAccountManager getSizeTypeString:PACollectionSizeType2X5] image:nil tag:PACollectionSizeType2X5 target:self action:@selector(pushMenuItem:)],
                       [KxMenuItem menuItem:[PAAccountManager getSizeTypeString:PACollectionSizeType3X3] image:nil tag:PACollectionSizeType3X3 target:self action:@selector(pushMenuItem:)],
                       [KxMenuItem menuItem:[PAAccountManager getSizeTypeString:PACollectionSizeType3X4] image:nil tag:PACollectionSizeType3X4 target:self action:@selector(pushMenuItem:)],
                       [KxMenuItem menuItem:[PAAccountManager getSizeTypeString:PACollectionSizeType3X5] image:nil tag:PACollectionSizeType3X5 target:self action:@selector(pushMenuItem:)],
                       [KxMenuItem menuItem:[PAAccountManager getSizeTypeString:PACollectionSizeType4X4] image:nil tag:PACollectionSizeType4X4 target:self action:@selector(pushMenuItem:)]];
    
    }
    return _menuItems;
}
- (void)viewDidLoad {
    [super viewDidLoad];
 
    [self setupBaseView];
    [self setUpNotification];
    [self setUpNav];
    
   }

- (void)setUpNotification{
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addChart:) name:PAChartListVCItemClickNotification object:nil];
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteChart:) name:PACurrentChartDeleteNotification object:nil];
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addChartGroups:) name:PAGroupChartADDNotification object:nil];
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteChartGroups:) name:PAGroupChartDeleteNotification object:nil];
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateChart:) name:PACurrentChartUpdateNotification object:nil];
    
//     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resizeBtn:) name:@"resizeBtn" object:nil];
    
}

- (void)setUpNav{
    
    UIBarButtonItem *rightButton =  [[UIBarButtonItem alloc] initWithTitle:@"Size" style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonItemClick:)];
    UIBarButtonItem *viewTypeButton = [[UIBarButtonItem alloc] initWithTitle:@"Graph" style:UIBarButtonItemStylePlain target:self action:@selector(viewTypeBtnClick:)];
    UIBarButtonItem *addGroupBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:@selector(editGroupBtnClick:)];
    
    self.navigationItem.rightBarButtonItems = @[rightButton,addGroupBtn];
    NSInteger idx = [PAAccountManager loadCurrentDockSize];
    self.navigationItem.rightBarButtonItems[0].title =[PAAccountManager getSizeTypeString:idx];
    //setUpSegmentControl
    NSString *rememberGroup = [PAAccountManager loadCurrentGroupName];
    if(rememberGroup==nil) rememberGroup = @"Default";
    HMSegmentedControl *segmentedControl = [[HMSegmentedControl alloc] initWithSectionTitles:self.chartGroups];
    segmentedControl.frame = CGRectMake(160, 16,self.view.frame.size.width-320, 40);
    segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth;
    segmentedControl.backgroundColor = [UIColor clearColor];
    segmentedControl.selectionIndicatorHeight = 4.0f;
    segmentedControl.segmentEdgeInset = UIEdgeInsetsMake(0, 12, 0, 12);
    segmentedControl.selectionIndicatorColor =[UIColor colorWithRed:0.000 green:0.478 blue:1.000 alpha:1.000];
     segmentedControl.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor darkTextColor],NSFontAttributeName:[UIFont systemFontOfSize:16.0f]};
    segmentedControl.selectedTitleTextAttributes = @{NSForegroundColorAttributeName : segmentedControl.selectionIndicatorColor,NSFontAttributeName:[UIFont systemFontOfSize:20.0f]};
    segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleBox;
    segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
    segmentedControl.verticalDividerColor = [UIColor blackColor];
    segmentedControl.verticalDividerWidth = 1.0f;
    segmentedControl.shouldAnimateUserSelection = YES;
    segmentedControl.segmentWidthStyle = HMSegmentedControlSegmentWidthStyleDynamic;
    self.segmentedControl = segmentedControl;
    [segmentedControl addTarget:self action:@selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged];
    if (rememberGroup!=nil&&[self.chartGroups indexOfObject:rememberGroup]!=NSNotFound) {
        segmentedControl.selectedSegmentIndex =[self.chartGroups indexOfObject:rememberGroup];
    }else{
        segmentedControl.selectedSegmentIndex = HMSegmentedControlNoSegment;
    }
    
    self.navigationItem.titleView = self.segmentedControl;
}

- (void)rightButtonItemClick:(UIBarButtonItem *)sender {
    
    [KxMenu showMenuInView:self.view
                  fromRect:CGRectMake(self.view.frame.size.width-44, 64, 0, 0)
                 menuItems:self.menuItems];
    
}
/**
 *  设置控制器view属性
 */
- (void)setupBaseView
{
    self.collectionView.emptyDataSetSource = self;
    self.collectionView.emptyDataSetDelegate = self;
    self.collectionView.backgroundColor = PAGlobalBg;
    
    // 垂直方向上永远有弹簧效果
    self.collectionView.alwaysBounceVertical = NO;
    [self.collectionView registerClass:[PAWKWebViewCell class] forCellWithReuseIdentifier:@"wkwebviewcell"];

}


-(void)addChart:(NSNotification *)notice{
    ChartConfig *config = notice.userInfo[@"chartConfig"];
    [self.chartConfigs addObject:config];
     NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.chartConfigs.count-1 inSection:0];
    [self.collectionView insertItemsAtIndexPaths:@[indexPath]];
//    PAWKWebViewCell *cell = (PAWKWebViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
//    cell.chartConfig = config;
//    NSURL *ndexURL = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html" subdirectory:@"Resource/pilotgraph"];
//
//    NSString *url = [NSString stringWithFormat:@"%@?host=%@&port=%lu&patth=%@&protocol=ws&token=%@&source=Mobile&configSource=Mobile",ndexURL.absoluteString,[PAAppContext sharedInstance].w_host,(unsigned long)[PAAppContext sharedInstance].w_port,[config.chartName urlEncode],self.token];
//    NSURL *indexURL = [NSURL URLWithString:url];
//    [cell setUrl:indexURL];
    if (self.chartConfigs.count<=1) {
        [self.collectionView reloadEmptyDataSet];
    }
}

-(void)updateChart:(NSNotification *)notice{
    ChartConfig *config = notice.userInfo[@"chartConfig"];
    NSInteger index =  [[self.chartConfigs  valueForKey:@"chartName"] indexOfObject:config.chartName];
    if (index==NSNotFound) {
        DDLogError(@"updateChart NSNotFound %@",config);
        return;
    }
    [self.chartConfigs replaceObjectAtIndex:index withObject:config];
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];

}


-(void)deleteChart:(NSNotification *)notice{
     NSInteger index = [notice.userInfo[@"index"] integerValue];
      NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
     [self.chartConfigs removeObjectAtIndex:index];
    [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
    if (index==0) {
        [self.collectionView reloadEmptyDataSet];
    }
    
}

-(void)resizeBtn:(NSNotification *)notice{
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        
//        NSArray *arr = self.collectionView.visibleCells;
//        [arr enumerateObjectsUsingBlock:^(PAWKWebViewCell   *obj, NSUInteger idx, BOOL * _Nonnull stop) {
//             [obj.contentView bringSubviewToFront:obj.closeBtn];
//        }];
////    NSInteger cellRow = [notice.userInfo[@"cellRow"] integerValue];
//////    NSInteger index = [notice.userInfo[@"index"] integerValue];
////    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:cellRow inSection:0];
////
////    PAWKWebViewCell *cell =(PAWKWebViewCell *) [self.collectionView cellForItemAtIndexPath:indexPath];
////    [cell.contentView bringSubviewToFront:cell.closeBtn];
//        
//    });
}

- (void)viewWillAppear:(BOOL)animated
{

    [super viewWillAppear:animated];
    [self setupLayout:self.view.frame.size.width height:self.view.frame.size.height orientation:self.interfaceOrientation];
    
}

#pragma mark - 处理屏幕的旋转
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    // 总宽度
    CGFloat totalWidth = self.view.frame.size.height;
    CGFloat totalHeight = self.view.frame.size.width;
    [self setupLayout:totalWidth height:totalHeight orientation:toInterfaceOrientation];

}

- (void)setupLayout:(CGFloat)totalWidth height:(CGFloat)totalHeight orientation:(UIInterfaceOrientation)orientation
{
    // 总列数
    int columns =  [self getCols];
    int rows = [self getRows];
    UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionViewLayout;
    // 每一行的最小间距
    CGFloat lineSpacing = 0;
    
     CGFloat interitemSpacing = 0;
     CGFloat width = (totalWidth-interitemSpacing*(columns+1))/columns-1;
     CGFloat height = (totalHeight-lineSpacing*(rows+1)-64)/rows-1;
    layout.itemSize = CGSizeMake(width, height);
    
    layout.minimumInteritemSpacing = interitemSpacing;
    layout.minimumLineSpacing = lineSpacing;
    // 设置cell与CollectionView边缘的间距
    layout.sectionInset = UIEdgeInsetsMake(lineSpacing, interitemSpacing, lineSpacing, interitemSpacing);
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.chartConfigs.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PAWKWebViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"wkwebviewcell" forIndexPath:indexPath];
//    PAWKWebViewCell *cell = [[PAWKWebViewCell alloc] init];
//    PAWKWebViewCell *cell = [PAWKWebViewCell cellWithCollection:collectionView forIndexPath:indexPath];
//       [cell bringSubviewToFront:cell.closeBtn];
    cell.closeDelegate = self;
        ChartConfig *chartConfig =self.chartConfigs[indexPath.row];
    if (self.viewType == PAViewTypeGraph) {
       
        NSURL *ndexURL = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html" subdirectory:@"Resource/pilotgraph"];
        
        NSString *url = [NSString stringWithFormat:@"%@?host=%@&port=%lu&patth=%@&protocol=ws&token=%@&source=Mobile&configSource=Mobile",ndexURL.absoluteString,[PAAppContext sharedInstance].w_host,(unsigned long)[PAAppContext sharedInstance].w_port,[chartConfig.chartName urlEncode],self.token];
        NSURL *indexURL = [NSURL URLWithString:url];
        cell.chartConfig = chartConfig;
        cell.url = indexURL;
        
//        [cell.webView loadRequest:[NSURLRequest requestWithURL:indexURL]];
    }else{
  
        NSURL *ndexURL = [[NSBundle mainBundle] URLForResource:@"grid" withExtension:@"html" subdirectory:@"RealTimeDataGrid"];
        
        NSString *url = [NSString stringWithFormat:@"%@?host=%@&port=%lu&path=%@&protocol=ws&token=%@&source=Mobile&configSource=Mobile",ndexURL.absoluteString,[PAAppContext sharedInstance].w_host,(unsigned long)[PAAppContext sharedInstance].w_port,[chartConfig.chartName urlEncode],self.token];
        NSURL *indexURL = [NSURL URLWithString:url];
        cell.url = indexURL;
        cell.chartConfig = chartConfig;
//        [cell.webView loadRequest:[NSURLRequest requestWithURL:indexURL]];
    }
    
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
   ChartConfig *chartConfig =self.chartConfigs[indexPath.row];
    PAWKWebViewCell *cell =  (PAWKWebViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    PAChartDetailVC *chartDetailVC =  [[PAChartDetailVC alloc] init];
//    chartDetailVC.webViewCell = cell;
    chartDetailVC.webView = cell.webView;
    chartDetailVC.viewType = self.viewType;
    chartDetailVC.chartConfig = chartConfig;
//    chartDetailVC.title = chartConfig.chartName;
    self.selectIndex = indexPath;
    self.selectCellFrame =cell.webView.frame;
    [self.navigationController pushViewController:chartDetailVC animated:YES];
    
}

#pragma mark - DZNEmptyDataSetSource Methods

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    NSString *text = @"No chart graph";
    
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.alignment = NSTextAlignmentCenter;
    
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:17.0],
                                 NSForegroundColorAttributeName: [UIColor colorWithRed:170/255.0 green:171/255.0 blue:179/255.0 alpha:1.0],
                                 NSParagraphStyleAttributeName: paragraphStyle};
    
    return [[NSMutableAttributedString alloc] initWithString:text attributes:attributes];
}

- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
{
    NSString *text = @"To show a list of chart graph, swipe right to add a chart";
    
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.alignment = NSTextAlignmentCenter;
    
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:15.0],
                                 NSForegroundColorAttributeName: [UIColor colorWithRed:170/255.0 green:171/255.0 blue:179/255.0 alpha:1.0],
                                 NSParagraphStyleAttributeName: paragraphStyle};
    
    return [[NSMutableAttributedString alloc] initWithString:text attributes:attributes];
}

- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
{
    return nil;
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
{
    return [UIImage imageNamed:@"placeholder_kickstarter"];
}



#pragma mark - LXReorderableCollectionViewDataSource methods

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath{
         ChartConfig *chartConfig =self.chartConfigs[sourceIndexPath.item];
         [self.chartConfigs removeObjectAtIndex:sourceIndexPath.item];
         [self.chartConfigs insertObject:chartConfig atIndex:destinationIndexPath.item];
    
}

- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return NO;
}


-(int) getRows{
    PACollectionSizeType idx = [PAAccountManager loadCurrentDockSize];
    switch (idx) {
        case PACollectionSizeType1X2:
        case PACollectionSizeType2X2: {
            return 2;
            break;
        }
        case PACollectionSizeType1X3:
        case PACollectionSizeType2X3:
        case PACollectionSizeType3X3: {
            return 3;
            break;
        }
        case PACollectionSizeType2X4:
        case PACollectionSizeType3X4:
        case PACollectionSizeType4X4: {
            return 4;
            break;
        }
        case PACollectionSizeType1X5:
        case PACollectionSizeType2X5:
        case PACollectionSizeType3X5: {
            return 5;
            break;
        }

    }
    
}

-(int) getCols{
    PACollectionSizeType idx = [PAAccountManager loadCurrentDockSize];
    switch (idx) {
        case PACollectionSizeType1X2:
        case PACollectionSizeType1X3:
        case PACollectionSizeType1X5:{
            return 1;
            break;
        }
        case PACollectionSizeType2X2:
        case PACollectionSizeType2X3:
        case PACollectionSizeType2X4:
        case PACollectionSizeType2X5:{
            return 2;
            break;
        }
        case PACollectionSizeType3X3:
        case PACollectionSizeType3X4:
        case PACollectionSizeType3X5:{
            return 3;
            break;
        }
        case PACollectionSizeType4X4: {
            return 4;
            break;
        }
    }

    
    
}
-(void)dealloc{
    LOGMETHOD
     [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    if (self.selectIndex!=nil) {
        PAWKWebViewCell *cell =  (PAWKWebViewCell *)[self.collectionView cellForItemAtIndexPath:self.selectIndex];
        [cell.contentView addSubview:cell.webView];
        [cell.contentView bringSubviewToFront:cell.closeBtn];
        cell.webView.frame = self.selectCellFrame;
        [cell.webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(cell.webView.superview).with.insets(UIEdgeInsetsZero);
            
        }];

        self.selectIndex = nil;
    }
}

- (BOOL)checkSize:(NSInteger) size withDockSize:(NSInteger) dockSize
{
    if (size>dockSize) {
        [CRToastManager showNotificationWithMessage:@"already more than limit chart size!" completionBlock:^{
            
        }];
        return NO;
    }
    return YES;
}

- (void) pushMenuItem:(KxMenuItem *)sender
{

    NSInteger dockSize =  sender.tag;
    if(![self checkSize:self.chartConfigs.count withDockSize:dockSize]) return;
    [PAAccountManager saveDockSize:dockSize];
    self.navigationItem.rightBarButtonItems[0].title = sender.title;
    [self setupLayout:self.view.frame.size.width height:self.view.frame.size.height orientation:self.interfaceOrientation];
}

- (void)segmentedControlChangedValue:(HMSegmentedControl *)segmentedControl {
    NSInteger index = segmentedControl.selectedSegmentIndex;
    NSInteger dockSize = [PAAccountManager loadCurrentDockSize];
    //获取group下边groupChart
    ChartGroup *chartGroup = [PAGroupManager loadGroupByGroupName:self.chartGroups[index]];
    if (chartGroup==nil) {
        DDLogError(@"segmentedControlChangedValue loadGroupByGroupName error");
        return;
    }
    NSArray *charts =  chartGroup.chartConfigs;
    if (charts==nil) {
        DDLogError(@"segmentedControlChangedValue loadGroupByGroupName chartConfigs error");
        return;
    }
    if ([self checkSize:charts.count withDockSize:dockSize]) {
        
        NSMutableArray *newChartConfigs = [NSMutableArray arrayWithCapacity:charts.count];
        [charts enumerateObjectsUsingBlock:^(NSString  * obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSInteger index = [[PAAppContext sharedInstance].chartNames indexOfObject:obj];
            if (index==NSNotFound) {
                //如果服务器没有该config
                 DDLogError(@"segmentedControlChangedValue server miss chartConfigs");
                [CRToastManager showNotificationWithMessage:@"server chartConfigs missing,please reset chartConfigs!" completionBlock:^{
                    
                }];
                return ;
            }else{
                ChartConfig *chartConfig =  [PAAppContext sharedInstance].chartConfigs[index];
                //sendConfig
                [[PAWebSocketManager sharedInstance] sendMsg:chartConfig.config.mj_JSONString];
                
                [newChartConfigs addObject:chartConfig];
                
                
            }
            
            
            
        }];
        [PAChartConfigManager saveCurrentChartConfigs:newChartConfigs];
       [PAAccountManager saveGroupName:self.chartGroups[index]];
        
       //3.刷新右边collectionview
        [self.chartConfigs removeAllObjects];
        [self.chartConfigs addObjectsFromArray:[PAChartConfigManager loadCurrentChartConfigs]];
        [self.collectionView reloadData];
    }
    
    
    
}

- (void)editGroupBtnClick:(UIBarButtonItem *)sender {
    
    EditGroupVC *egroupVC = [EditGroupVC new];
    egroupVC.title = @"Groups";
    PANavgationVC *recipeNav = [[PANavgationVC alloc] initWithRootViewController:egroupVC];
    recipeNav.modalPresentationStyle = UIModalPresentationFormSheet;
    [self presentViewController:recipeNav animated:YES completion:nil];
    
}
- (void)viewTypeBtnClick:(UIBarButtonItem *)sender {
    
    if ([sender.title isEqualToString:@"Graph"]) {
        self.viewType = PAViewTypeGrid;
        sender.title = @"Grid";
    }else{
         self.viewType = PAViewTypeGraph;
         sender.title = @"Graph";
    }
    [self.collectionView reloadData];
    
}


-(void)addChartGroups:(NSNotification *)notice{
    ChartGroup *chartGroup = notice.userInfo[@"chartGroup"];
    [self.chartGroups addObject:chartGroup.groupName];
    self.segmentedControl.sectionTitles = self.chartGroups;
    [self.segmentedControl setNeedsDisplay];
}

-(void)deleteChartGroups:(NSNotification *)notice{
    NSString *groupName = notice.userInfo[@"groupName"];
    [self.chartGroups removeObject:groupName];
    self.segmentedControl.sectionTitles = self.chartGroups;
    [self.segmentedControl setNeedsDisplay];
}

-(void)webviewCellclickCloseItem:(PAWKWebViewCell *)cell{
    NSIndexPath *path = [self.collectionView indexPathForCell:cell];
     ChartConfig *config = self.chartConfigs[path.row];
    [self.chartConfigs removeObjectAtIndex:path.row];
    [self.collectionView deleteItemsAtIndexPaths:@[path]];
    if (path.row==0) {
        [self.collectionView reloadEmptyDataSet];
    }
    //删除数据
    [PAChartConfigManager deleteCurrentChartConfigByChartName:config.chartName];
    NSString *groupName = [PAAccountManager loadCurrentGroupName];
    //判断当前所在的group,同步删除group中的chart
    if (groupName!=nil) {
        [PAGroupManager updateGroup:groupName withChartNames:[self.chartConfigs valueForKey:@"chartName"]];
    }
}
@end
